package middleware

import (
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func Logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		query := c.Request.URL.RawQuery

		c.Next()
		status := c.Writer.Status()

		// 仅在请求失败时记录日志
		if status >= 400 {
			zap.L().Error("请求失败",
				zap.Int("status", status),
				zap.String("method", c.Request.Method),
				zap.String("path", path),
				zap.String("query", query),
				zap.String("ip", c.ClientIP()),
				zap.String("user-agent", c.Request.UserAgent()),
				zap.Duration("latency", time.Since(start)),
				zap.String("start_time", start.Format("2006-01-02 15:04:05")),
			)
		}
	}
}
